package com.zry.yard.ui.activity

import android.content.Intent
import com.yzq.zxinglibrary.common.Constant
import com.zry.yard.R
import com.zry.yard.databinding.ActivityTracingCodeQueryBinding
import com.zry.yard.presenter.TracingCodeQueryPresenter
import com.zry.yard.ui.base.BaseActivity
import kotlinx.android.synthetic.main.activity_tracing_code_query.*
import kotlinx.android.synthetic.main.common_title.*


class TracingCodeQueryActivity : BaseActivity() {
    private var tracingCodeQueryBinding: ActivityTracingCodeQueryBinding? = null
    private var tracingCodeQueryPresenter: TracingCodeQueryPresenter? = null
    var title = ""
    override fun getLayoutId(): Int {
        return R.layout.activity_tracing_code_query
    }

    override fun initData() {
        title = intent.getStringExtra("title")
        titleCenterText.text = title
        commonLeftLinearLayout.setOnClickListener { finish() }
        tracingCodeQueryBinding = viewDataBinding as ActivityTracingCodeQueryBinding
        tracingCodeQueryPresenter = TracingCodeQueryPresenter(this)
        tracingCodeQueryBinding?.handlerClick = tracingCodeQueryPresenter

        initView()
    }

    private fun initView() {
        when (title) {
            "追溯码查询" -> scanCodeET.hint = "手动输入包装上的追溯码/扫描商品二维码"
            "流通码查询" -> scanCodeET.hint = "手动输入包装上的流通码/扫描商品二维码"
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        when (requestCode) {
            0 -> {
                val resultStringCode = getResultCode(data.getStringExtra(Constant.CODED_CONTENT))
                when (title) {
                    "流通码查询" -> {
                        tracingCodeQueryPresenter?.getLongCirculationCode(resultStringCode.trim())
                    }
                    "追溯码查询" -> {
                        tracingCodeQueryPresenter?.getLongTraceCode(resultStringCode.trim())
                    }
                }
            }
        }
    }


    private fun getResultCode(sourceStr: String): String {
        val sourceStrArray = sourceStr.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        return sourceStrArray[sourceStrArray.size - 1]
    }
}
